package com.hong.intecepter;

import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * @Author csh
 * @Description 功能描述:http握手拦截器，可以通过这个类的方法获取request,和response
 * @Date 2018/9/15 15:36
 */
public class HttpHandShakeIntecepter implements HandshakeInterceptor {
    /**
     * 握手前
     * @param serverHttpRequest
     * @param serverHttpResponse
     * @param webSocketHandler
     * @param
     * @return
     * @throws Exception
     */
    @Override
    public boolean beforeHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Map<String, Object> attrbuite) throws Exception {
        System.out.println("[握手拦截器]beforeHandshake");
        if(serverHttpRequest instanceof ServletServerHttpRequest){
            ServletServerHttpRequest servletRequest = (ServletServerHttpRequest)serverHttpRequest;
            HttpSession session  = servletRequest.getServletRequest().getSession();
            String sessionId = session.getId();
            System.out.println("[握手拦截器]beforeHandshake-sessionId"+sessionId);
            attrbuite.put("sessionId",sessionId);

        }
        return true;
    }

    /**
     * 握手后
     * @param serverHttpRequest
     * @param serverHttpResponse
     * @param webSocketHandler
     * @param e
     */
    @Override
    public void afterHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Exception e) {
        System.out.println("[afterHandshake握手拦截器]");
        if(serverHttpRequest instanceof ServletServerHttpRequest){
            ServletServerHttpRequest servletRequest = (ServletServerHttpRequest)serverHttpRequest;
            HttpSession session  = servletRequest.getServletRequest().getSession();
            String sessionId = session.getId();
            System.out.println("[握手拦截器]afterHandshake-sessionId"+sessionId);

        }


    }
}
